package com.XDApp.xdbase.activitys;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.bean.FreeWalker;
import com.XDApp.xdbase.bean.FreeWalkerEntity;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.IRequest;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class ChangePhoneActivity extends BaseActivity implements OnClickListener {
	private final String TAG = "ChangePwdActivity";
	private ImageView iv_back;
	private TextView tv_title, tv_right, tv_oldPhone;
	private EditText et_phone, et_code;
	private Button bt_code;
	String phone, code;

	@Override
	protected void initViews() {
		setContentView(R.layout.activity_changephone);

		iv_back = (ImageView) findViewById(R.id.title_back);
		tv_title = (TextView) findViewById(R.id.title_text);
		tv_oldPhone = (TextView) findViewById(R.id.tv_oldPhone);
		tv_right = (TextView) findViewById(R.id.title_right);
		et_phone = (EditText) findViewById(R.id.et_phone);
		et_code = (EditText) findViewById(R.id.et_code);
		bt_code = (Button) findViewById(R.id.bt_code);

		iv_back.setOnClickListener(this);
		tv_right.setOnClickListener(this);
		bt_code.setOnClickListener(this);
	}

	@Override
	protected void initEvents() {
		tv_right.setText("确定");
		tv_right.setTextColor(Color.WHITE);
		tv_title.setText("修改手机号");
		String phone = getIntent().getStringExtra("phone");
		tv_oldPhone.setText(TextUtils.isEmpty(phone) ? "未绑定手机号" : phone);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		case R.id.bt_code:// 获取验证码
			phone = et_phone.getText().toString().trim();
			if (TextUtils.isEmpty(phone)) {
				CRToast.show(ChangePhoneActivity.this, "请填写手机号");
				return;
			}
			if (!isMobilePhone(phone)) {
				CRToast.show(ChangePhoneActivity.this, "请输入正确的手机号");
				return;
			}

			getVerifyData(phone);

			break;
		case R.id.title_right:// 确定按钮
			phone = et_phone.getText().toString().trim();
			code = et_code.getText().toString().trim();

			if (TextUtils.isEmpty(phone)) {
				CRToast.show(ChangePhoneActivity.this, "手机号码不能为空");
				return;
			}

			if (TextUtils.isEmpty(code)) {
				CRToast.show(ChangePhoneActivity.this, "验证码不能为空");
				return;
			}

			checkVerify(phone, code, new IRequest<Boolean>() {

				@Override
				public void request(Boolean t) {
					updateSex(phone, getIntent().getStringExtra("userID"));
				}
			});

			break;
		default:
			break;
		}
	}

	/**
	 * 获取验证码
	 * @param isEmail
	 * @param phone
	 */
	private void getVerifyData(final String phone) {
		if (CommonUtil.checkNetState(getBaseContext())) {
			RequestParams params = new RequestParams();
			params.put("phone", phone);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.GETVERIFYCODE, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.e(TAG, content);
					JSONObject obj = new JSONObject().parseObject(content);
					String data = obj.getString("data");
					JSONObject obj1 = new JSONObject().parseObject(data);
					String isUserReg = obj1.getString("isUserReg");
					Log.e(TAG, isUserReg);

					if ("0".equals(isUserReg)) {
						CRToast.show(getBaseContext(), "验证码已经发送给手机");
					} else {
						CRToast.show(getBaseContext(), "该手机号已经被注册");
						return;
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(getBaseContext(), R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	// TODO 访问网络获取数据
	private void checkVerify(final String phone, String code, final IRequest<Boolean> iRequest) {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("phoneNum", phone);
			params.put("verifyCode", code);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.CHECKVERIFYCODE, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.e(TAG, content);
					// 判断返回数据是否正确
					if (TextUtils.isEmpty(content)) {
						CommonUtil.showToast(mContext, "获取数据失败");
						return;
					}

					JSONObject obj = new JSONObject().parseObject(content);
					String state = obj.getString("state");
					if ("1".equals(state)) {
						iRequest.request(true);
					} else {
						iRequest.request(false);
						CommonUtil.showToast(getBaseContext(), "验证码错误!");
						return;
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	/**
	 * 验证验证码
	 */
	/*private void checkVerify() {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("Phone", phone);
			params.put("userID", name);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.UPDATE_SEX, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.i(TAG, content);
					JSONObject obj = new JSONObject().parseObject(content);
					String data = obj.getString("data");
					FreeWalkerEntity parseObject = JSON.parseObject(data, FreeWalkerEntity.class);

					// 判断返回数据是否正确
					if (null != parseObject) {
						List<FreeWalker> list = parseObject.getList();
						// 关闭掉这个Activity
					} else {
						CommonUtil.showToast(mContext, "获取数据失败");
					}
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}*/

	// TODO 访问网络获取数据
	private void updateSex(String phone, String name) {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("Phone", phone);
			params.put("userID", name);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.UPDATE_SEX, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.i(TAG, content);
					JSONObject obj = new JSONObject().parseObject(content);
					String data = obj.getString("data");
					FreeWalkerEntity parseObject = JSON.parseObject(data, FreeWalkerEntity.class);

					// 判断返回数据是否正确
					if (null != parseObject) {
						List<FreeWalker> list = parseObject.getList();
						// 关闭掉这个Activity
					} else {
						CommonUtil.showToast(mContext, "获取数据失败");
					}
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	/**
	 * 判断手机号码是否合法.
	 */
	private boolean isMobilePhone(String address) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,2,5-9]))\\d{8}$");
		Matcher m = p.matcher(address);
		return m.matches();
	}
}
